library(optparse)
library(dplyr)
library(circlize)

option_list <- list(
  make_option("--b", default = "gene_fusion.bed", type = "character", help = "gene fusion bed file"),
  make_option("--g", default = "", type = "character", help = "gene"),
  make_option("--o", default = "", type = "character", help = "output png file")
)
opt <- parse_args(OptionParser(option_list = option_list))

Args <- commandArgs(T)
gene=opt$g
library(dplyr)
library(circlize)
options(stringsAsFactors = F)
fusion_bed=read.table(opt$b,header=T)
gene_chr=unique(fusion_bed[which(fusion_bed$Gensymbol1==gene),'chr1'])
fusion_bed[is.na(fusion_bed)] <-'NA_gene'
fusion_bed=unique(fusion_bed)
#========================format data===========================
data=fusion_bed[which(fusion_bed$Gensymbol1==gene|fusion_bed$Genesymbol2==gene),]
data1=data[which(data$Gensymbol1==gene),]
data1$Genesymbol2=paste(data1$Genesymbol2,"\n","(",data1$chr2,":",data1$start2,":",data1$strand2,")","\n","(","downstream",")")
data2=data[which(data$Genesymbol2==gene),]
data2$Gensymbol1=paste(data2$Gensymbol1,"\n","(",data2$chr1,":",data2$start1,":",data2$strand1,")","\n","(","upstream",")")
data=rbind(data1,data2)
#============================group genesymbol2 and max==================
#data=data[,c("Gensymbol1","Genesymbol2","frequency")]
data$frequency=as.numeric(data$frequency)
data<- data %>%group_by(Gensymbol1,Genesymbol2) %>%filter(frequency==max(frequency))
data=data[!duplicated(data[,c('Gensymbol1','frequency','Genesymbol2')]),]
data=data[order(data$chr1,data$chr2),]
rgenes=unique(c(data$Gensymbol1,data$Genesymbol2))
gene_bed=data.frame(genename=rgenes,start=rep(1,length(rgenes)),end=rep(100,length(rgenes)))
#===================format bed==================================
data$frequency=as.numeric(data$frequency)
bed1=data.frame(genename=gene,start=rep(48,length(data$Gensymbol1)),end=rep(52,length(data$Gensymbol1)))
b1=as.data.frame(data[which(data$Gensymbol1!=gene),c("Gensymbol1","frequency")])
b2=as.data.frame(data[which(data$Genesymbol2!=gene),c("Genesymbol2","frequency")])
names(b1)[1]="Genesymbol"
names(b2)[1]="Genesymbol"
bed2_tmp=rbind(b1,b2)
bed2_tmp[which(bed2_tmp$frequency>10),'frequency']=10
bed2=data.frame(genename=bed2_tmp$Genesymbol,start=48-4*bed2_tmp$frequency,end=52+4*bed2_tmp$frequency)


#============================get frequency values=======================
genes=gene_bed$genename
data$frequency3=paste("case=",data$frequency,sep="")
freq=c()
for(i in genes){
  if(i==gene){
    freq=c(freq,'')}else{
    freq=c(freq,data[which(data$Gensymbol1==i|data$Genesymbol2==i),'frequency3'])
  }

}
gene_bed[which(gene_bed$genename==gene),'genename']=paste(gene,"\n","(",gene_chr,")",sep="")
bed1[which(bed1$genename==gene),'genename']=paste(gene,"\n","(",gene_chr,")",sep="")
bed2[which(bed2$genename==gene),'genename']=paste(gene,"\n","(",gene_chr,")",sep="")
#========================================================================
#png(file="plot2.png",width=600*5,height=3000,res=72*4)
pdf(file=opt$o,width=13,height=13,onefile = FALSE)
circos.clear()
circos.par(canvas.xlim =c(-1.3,1.3),canvas.ylim = c(-1.3,1.3),cell.padding = c(0.02,0,0.02,0))
circos.genomicInitialize(gene_bed,plotType =NULL)
colors=rand_color(nrow(bed1),luminosity="dark",transparency = 0.5)
circos.track(ylim = c(0,1),
             bg.col =colors(),
             panel.fun = function(x, y) {
               xlim = get.cell.meta.data("xlim")
               ylim = get.cell.meta.data("ylim")
               sector.name = get.cell.meta.data("sector.index")
               initialRates=freq
               circos.text(mean(xlim), ylim[1]+1.3, sector.name, facing = "reverse.clockwise", niceFacing = TRUE,adj = c(1,1),cex =1)
               circos.text(CELL_META$xcenter, CELL_META$ycenter, freq[CELL_META$sector.numeric.index], facing ="inside", niceFacing = TRUE,cex =1.2)
             },
             bg.border = NA, track.height = 0.05)

circos.genomicLink(bed1, bed2, col =colors, border = NA)

dev.off()

